package com.casic.ops.controller;

import com.casic.ops.annotation.IgnoreAuth;
import com.casic.ops.annotation.IgnoreWrapper;
import com.casic.ops.annotation.RestWrapper;
import com.casic.ops.consts.Const;
import com.casic.ops.consts.download.FileDownloadType;
import com.casic.ops.entity.domain.OpsResult;
import com.casic.ops.entity.dto.FileDownloadDTO;
import com.casic.ops.entity.request.FileDownloadRequest;
import com.casic.ops.service.api.FileDownloadService;
import com.casic.ops.utils.OpsAssert;
import com.orion.exception.NotFoundException;
import com.orion.servlet.web.Servlets;
import com.orion.utils.Strings;
import com.orion.utils.collect.Maps;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName ops-platform
 * @Description 文件下载
 * @Author mianbin
 * @Date 2022/5/31 10:58
 * @Version 1.0
 **/
@RestController
@RestWrapper
@RequestMapping("/ops/api/file-download")
public class FileDownloadController {

    @Resource
    private FileDownloadService fileDownloadService;

    /**
     * 下载文件 检查文件存在以及权限
     */
    @RequestMapping("/token")
    public String getToken(@RequestBody FileDownloadRequest request) {
        Long id = OpsAssert.notNull(request.getId());
        FileDownloadType type = OpsAssert.notNull(FileDownloadType.of(request.getType()));
        return fileDownloadService.getDownloadToken(id, type);
    }

    /**
     * 下载文件
     */
    @RequestMapping("/{token}/exec")
    @IgnoreWrapper
    @IgnoreAuth
    public void downloadLogFile(@PathVariable String token, HttpServletResponse response) throws IOException {
        try {
            fileDownloadService.execDownload(token, response);
        } catch (NotFoundException e) {
            // 文件未找到
            Servlets.transfer(response, Const.EMPTY.getBytes(), Strings.bytes(Const.UNKNOWN, Const.UTF_8));
        }
    }

    @GetMapping("/{token}/view")
    @IgnoreWrapper
    @IgnoreAuth
    public Map<String,Object> viewLogStr(@PathVariable String token, HttpServletResponse response) {
        String data = Optional.ofNullable(token)
                .map(var -> fileDownloadService.getPathByDownloadToken(var))
                .map(FileDownloadDTO::getFilePath).map(var -> {
                    try {
                        return FileUtils.readFileToString(new File(var));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return "";
                }).get();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", 200);
        dataMap.put("msg", "success");
        dataMap.put("data", data);
        return dataMap;
    }

}
